import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useMenuStore } from '@/stores/menu'
import { error } from '@/utils/toast'
import { hasPagePermission } from '@/utils/permissions'

// 基础路由（无需权限）
const basicRoutes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/index.vue'),
    meta: {
      title: '登录',
      requiresAuth: false
    }
  },
  {
    path: '/',
    name: 'Layout',
    component: () => import('@/layouts/MainLayout.vue'),
    redirect: '/video/live',
    meta: {
      requiresAuth: true
    },
    children: [
      {
        path: '/video',
        name: 'Video',
        redirect: '/video/live',
        meta: {
          title: '视频监控',
          icon: 'VideoCamera'
        },
        children: [
          {
            path: '/video/live',
            name: 'VideoLive',
            component: () => import('@/views/video/live/index.vue'),
            meta: {
              title: '实时预览',
              icon: 'VideoPlay'
            }
          },
          {
            path: '/video/map',
            name: 'VideoMap',
            component: () => import('@/views/video/map/index.vue'),
            meta: {
              title: '电子地图',
              icon: 'MapLocation'
            }
          },
          {
            path: '/video/camera',
            name: 'VideoCamera',
            component: () => import('@/views/video/camera/index.vue'),
            meta: {
              title: '摄像机设置',
              icon: 'Camera'
            }
          },
          {
            path: '/video/playback',
            name: 'VideoPlayback',
            component: () => import('@/views/video/playback/index.vue'),
            meta: {
              title: '录像回放',
              icon: 'VideoPause'
            }
          }
        ]
      },

      {
        path: '/alarm',
        name: 'Alarm',
        component: () => import('@/views/alarm/index.vue'),
        meta: {
          title: '报警系统',
          icon: 'Bell'
        }
      },
      {
        path: '/device',
        name: 'Device',
        redirect: '/device/stream',
        meta: {
          title: '设备管理',
          icon: 'Monitor'
        },
        children: [
          {
            path: '/device/stream',
            name: 'DeviceStream',
            component: () => import('@/views/device/stream/index.vue'),
            meta: {
              title: '流媒体管理',
              icon: 'VideoCamera'
            }
          },
          {
            path: '/device/nmc',
            name: 'DeviceNMC',
            component: () => import('@/views/device/nmc/index.vue'),
            meta: {
              title: 'NMC管理',
              icon: 'Setting'
            }
          }
        ]
      },
      {
        path: '/system',
        name: 'System',
        redirect: '/system/user',
        meta: {
          title: '系统管理',
          icon: 'Setting'
        },
        children: [
          {
            path: '/system/user',
            name: 'SystemUser',
            component: () => import('@/views/system/user/index.vue'),
            meta: {
              title: '用户管理',
              icon: 'User'
            }
          },
          {
            path: '/system/role',
            name: 'SystemRole',
            component: () => import('@/views/system/role/index.vue'),
            meta: {
              title: '角色管理',
              icon: 'UserFilled'
            }
          },
        ]
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/index.vue'),
    props: { errorCode: 403 },
    meta: {
      title: '无权限访问',
      requiresAuth: false
    }
  },
  {
    path: '/404',
    name: 'NotFound',
    component: () => import('@/views/error/index.vue'),
    props: { errorCode: 404 },
    meta: {
      title: '页面不存在',
      requiresAuth: false
    }
  },
  {
    path: '/:pathMatch(.*)*',
    redirect: '/404'
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(),
  routes: basicRoutes
})

// 检查页面权限
const checkPagePermission = (pagePath: string, userPagePrivilege: number): boolean => {
  return hasPagePermission(pagePath, userPagePrivilege)
}

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  const authStore = useAuthStore()
  const menuStore = useMenuStore()
  
  // 调试信息
  console.log('路由守卫:', {
    to: to.path,
    from: from.path,
    isLoggedIn: authStore.isLoggedIn,
    requiresAuth: to.meta.requiresAuth,
    user: authStore.user
  })
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 新华冶金智慧安防平台`
  }

  // 如果访问登录页且已登录，跳转到电子地图页面
  // 在开发模式下，可以通过添加 ?force=true 参数强制访问登录页
  // 注释掉以下代码以允许在开发时直接访问登录页
  // if (to.path === '/login' && authStore.isLoggedIn && !to.query.force) {
  //   console.log('用户已登录，重定向到实时视频页面')
  //   next('/video/live')
  //   return
  // }

  // 如果页面需要认证
  if (to.meta.requiresAuth !== false) {
    if (!authStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next('/login')
      return
    }

    // 初始化用户信息和菜单
    // if (!authStore.user) {
    //   try {
    //     await authStore.initAuth()
    //     await menuStore.initMenus()
    //   } catch (error) {
    //     console.error('Init auth failed:', error)
    //     next('/login')
    //     return
    //   }
    // }
  }

  // 检查页面权限（排除不需要权限的页面）
  if (to.path !== '/login' && to.path !== '/403' && to.path !== '/404' && to.meta.requiresAuth !== false) {
    const userPagePrivilege = authStore.user?.pagePrivilege || 0
    const hasPermission = checkPagePermission(to.path, userPagePrivilege)
    
    // 调试信息
    console.log('权限检查:', {
      path: to.path,
      userPagePrivilege,
      hasPermission,
      user: authStore.user,
      permissions: authStore.permissions
    })
    
    if (!hasPermission) {
      error('没有权限访问该页面')
      next('/403')
      return
    }
  }

  // 设置当前激活菜单
  if (to.path !== '/login') {
    menuStore.setActiveMenu(to.path)
  }

  next()
})

// 路由后置守卫
router.afterEach((to) => {
  // 这里可以添加页面访问统计、埋点等逻辑
  console.log(`Navigate to: ${to.path}`)
})

export default router